package com.cn.kabalifeuser.ui;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.baidu.location.PoiRegion;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.base.MyApplication;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.config.SPLocationData;
import com.cn.kabalifeuser.event.RxBus;
import com.cn.kabalifeuser.event.RxBusBean;
import com.cn.kabalifeuser.service.LocationService;
import com.cn.kabalifeuser.ui.integral.FragmentIntegral;
import com.cn.kabalifeuser.ui.login.bean.LoginBean;
import com.cn.kabalifeuser.ui.my.FragmentMy;
import com.cn.kabalifeuser.ui.my.bean.MyUserInfoBean;
import com.cn.kabalifeuser.ui.order.FragmentOrder;
import com.cn.kabalifeuser.ui.release.FragmentRelease;
import com.cn.kabalifeuser.ui.service.FragmentService;
import com.cn.kabalifeuser.utils.ExampleUtil;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.PermissionsUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.utils.SPUtil;
import com.kongzue.dialog.v2.SelectDialog;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends IBaseActivity<MainActivityView, MainActivityPresenter> implements MainActivityView {


    @BindView(R.id.fragmentContent)
    FrameLayout fragmentContent;
    @BindColor(R.color.text_909090)
    int normalColor;
    @BindColor(R.color.main_color)
    int selectedColor;
    @BindView(R.id.text_service)
    TextView textService;
    @BindView(R.id.text_integral)
    TextView textIntegral;
    @BindView(R.id.text_release)
    TextView textRelease;
    @BindView(R.id.text_order)
    TextView textOrder;
    @BindView(R.id.text_me)
    TextView textMe;


    private long exitTime = 0;//标记退出时间。
    private FragmentService service;
    private FragmentIntegral integral;
    private FragmentRelease release;
    private FragmentOrder order;
    private FragmentMy my;


    private final String TAG_FRAGMENT_PSERVICE = "service";
    private final String TAG_FRAGMENT_INTEGRAL = "integral";
    private final String TAG_FRAGMENT_RELEASE = "release";
    private final String TAG_FRAGMENT_ORDER = "order";
    private final String TAG_FRAGMENT_MY = "my";
    /**
     * 用户选中的fragment的tag
     */
    private String selectedFragmentTag;
    private FragmentManager fragmentManager;
    private LocationService locationService;

    @Override
    protected MainActivityPresenter createPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void beforeInitView() {
        super.beforeInitView();
        mImmersionBar.statusBarDarkFont(false).init();
    }


    //极光推送需要的
    public static boolean isForeground = false;

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.cn.kabalifeuser.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    @Override
    public void onReLoggedIn(String msg) {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onUserInfoSuccess(MyUserInfoBean bean) {
        String str = bean.getResult().getId() + "1";
        JPushInterface.setAlias(getMe(), 1, str);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
//                    setCostomMsg(showMsg.toString());
                    RxToast.success(context.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
//        initDrawable(); //图标切换
        SPUtil.saveString(LoginHelper.IS_GUIDE_PAGE, "1");
        SPUtil.saveString(LoginHelper.IS_GUIDE_Age, "1");
        fragmentManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            service = (FragmentService) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_PSERVICE);
            integral = (FragmentIntegral) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_INTEGRAL);
            release = (FragmentRelease) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_RELEASE);
            order = (FragmentOrder) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_RELEASE);
            my = (FragmentMy) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_MY);

            selectedFragmentTag = savedInstanceState.getString("tag");
        }

        //默认选中主页
        selectedFragmentTag = TAG_FRAGMENT_PSERVICE;


        setSelectedFragment(selectedFragmentTag);
        setSelectedIcon(selectedFragmentTag);
        boolean str = PermissionsUtils.isAppliedPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION);
        if (str == false) {
            //        //动态获取权限。
            if (Build.VERSION.SDK_INT > 23) {
                MainActivityPermissionsDispatcher.initPermissionWithCheck(this);
            }
        }
        mPresenter.onUserInfoData(LoginHelper.getLonginData().getResult());

//        Set<String> set = new HashSet<>();
//        set.add("meridian_health_reminder");
//        set.add("solar_reminder");
//        set.add("four_seasons_reminder");
//        set.add("fitness_reminder");
//        JPushInterface.setTags(getMe(), 4, set);

    }


    /**
     * add添加
     *
     * @param fragment
     * @param tag
     */
    private void addFragment(Fragment fragment, String tag) {
        fragmentManager.beginTransaction().add(R.id.fragmentContent, fragment, tag).commit();
    }

    /**
     * 显示与隐藏
     *
     * @param fragment
     */
    private void showFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //先隐藏所有的fragment
        if (service != null) {
            transaction.hide(service);
        }
        if (integral != null) {
            transaction.hide(integral);
        }
        if (release != null) {
            transaction.hide(release);
        }
        if (order != null) {
            transaction.hide(order);
        }
        if (my != null) {
            transaction.hide(my);
        }
        transaction.show(fragment).commit();
        selectedFragmentTag = fragment.getTag();
    }

    private void setSelectedFragment(String selectedFragmentTag) {
        switch (selectedFragmentTag) {
            case TAG_FRAGMENT_PSERVICE:
                if (service == null) {
                    service = new FragmentService();
                    addFragment(service, TAG_FRAGMENT_PSERVICE);
                }
                showFragment(service);
                break;
            case TAG_FRAGMENT_INTEGRAL:
                if (integral == null) {
                    integral = new FragmentIntegral();
                    addFragment(integral, TAG_FRAGMENT_INTEGRAL);
                }
                showFragment(integral);
                break;
            case TAG_FRAGMENT_RELEASE:
                if (release == null) {
                    release = new FragmentRelease();
                    addFragment(release, TAG_FRAGMENT_RELEASE);
                }
                showFragment(release);
                break;
            case TAG_FRAGMENT_ORDER:
                if (order == null) {
                    order = new FragmentOrder();
                    addFragment(order, TAG_FRAGMENT_ORDER);
                }
                showFragment(order);
                break;
            case TAG_FRAGMENT_MY:
                if (my == null) {
                    my = new FragmentMy();
                    addFragment(my, TAG_FRAGMENT_MY);
                }
                showFragment(my);
                break;

            default:
                break;
        }
    }

    /**
     * 清除导航栏所有的选中状态。
     */
    private void clearSelection() {
        textIntegral.setTextColor(normalColor);
        textService.setTextColor(normalColor);
        textRelease.setTextColor(normalColor);
        textOrder.setTextColor(normalColor);
        textMe.setTextColor(normalColor);
    }

    public void setSelectedIcon(String selectedIcon) {
        clearSelection();  //TODO 先清除所有状态
        switch (selectedIcon) {
            case TAG_FRAGMENT_PSERVICE:
                textService.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_INTEGRAL:
                textIntegral.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_RELEASE:
                textRelease.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_ORDER:
                textOrder.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_MY:
                textMe.setTextColor(selectedColor);
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.layout_service, R.id.layout_integral, R.id.layout_release, R.id.layout_order, R.id.layout_me})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_service:
                if (!TAG_FRAGMENT_PSERVICE.equals(selectedFragmentTag)) {
                    mImmersionBar.statusBarDarkFont(false).init();
                    setSelectedFragment(TAG_FRAGMENT_PSERVICE);
                    setSelectedIcon(TAG_FRAGMENT_PSERVICE);
                }
                break;
            case R.id.layout_integral:
                if (!TAG_FRAGMENT_INTEGRAL.equals(selectedFragmentTag)) {
                    mImmersionBar.statusBarDarkFont(true).init();
                    setSelectedFragment(TAG_FRAGMENT_INTEGRAL);
                    setSelectedIcon(TAG_FRAGMENT_INTEGRAL);
                }
                break;
            case R.id.layout_release:
                if (!TAG_FRAGMENT_RELEASE.equals(selectedFragmentTag)) {
                    mImmersionBar.statusBarDarkFont(true).init();
                    setSelectedFragment(TAG_FRAGMENT_RELEASE);
                    setSelectedIcon(TAG_FRAGMENT_RELEASE);
                }
                break;
            case R.id.layout_order:
                if (!TAG_FRAGMENT_ORDER.equals(selectedFragmentTag)) {
                    mImmersionBar.statusBarDarkFont(true).init();
                    setSelectedFragment(TAG_FRAGMENT_ORDER);
                    setSelectedIcon(TAG_FRAGMENT_ORDER);
                }
                break;
            case R.id.layout_me:
                if (!TAG_FRAGMENT_MY.equals(selectedFragmentTag)) {
                    mImmersionBar.statusBarDarkFont(false).init();
                    setSelectedFragment(TAG_FRAGMENT_MY);
                    setSelectedIcon(TAG_FRAGMENT_MY);
                }
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onStart() {
        super.onStart();
        // -----------location config ------------
        if (LoginHelper.getLocationInfo() != null && LoginHelper.getLocationInfo().getIsLocation() == 1) {

        } else {
            locationService = ((MyApplication) getApplication()).locationService;
//        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
            locationService.registerListener(mListener);
            //注册监听
            int type = getIntent().getIntExtra("from", 0);
            if (type == 0) {
                locationService.setLocationOption(locationService.getDefaultLocationClientOption());
            } else if (type == 1) {
                locationService.start();
            }
            boolean str = PermissionsUtils.isAppliedPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION);
            LoggerUtils.e("检车start：" + str);
            if (str == true)
                locationService.start();// 定位SDK
        }
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        if (locationService != null) {
            locationService.unregisterListener(mListener); //注销掉监听
            locationService.stop(); //停止定位服务
        }
        super.onStop();
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        /**
         * 定位请求回调函数
         * @param location 定位结果
         */
        @Override
        public void onReceiveLocation(BDLocation location) {

            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                int tag = 1;
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                sb.append(location.getTime());
                sb.append("\nlocType : ");// 定位类型
                sb.append(location.getLocType());
                sb.append("\nlocType description : ");// *****对应的定位类型说明*****
                sb.append(location.getLocTypeDescription());
                sb.append("\nlatitude : ");// 纬度
                sb.append(location.getLatitude());
                sb.append("\nlongtitude : ");// 经度
                sb.append(location.getLongitude());
                sb.append("\nradius : ");// 半径
                sb.append(location.getRadius());
                sb.append("\nCountryCode : ");// 国家码
                sb.append(location.getCountryCode());
                sb.append("\nProvince : ");// 获取省份
                sb.append(location.getProvince());
                sb.append("\nCountry : ");// 国家名称
                sb.append(location.getCountry());
                sb.append("\ncitycode : ");// 城市编码
                sb.append(location.getCityCode());
                sb.append("\ncity : ");// 城市
                sb.append(location.getCity());
                sb.append("\nDistrict : ");// 区
                sb.append(location.getDistrict());
                sb.append("\nTown : ");// 获取镇信息
                sb.append(location.getTown());
                sb.append("\nStreet : ");// 街道
                sb.append(location.getStreet());
                sb.append("\naddr : ");// 地址信息
                sb.append(location.getAddrStr());
                sb.append("\nStreetNumber : ");// 获取街道号码
                sb.append(location.getStreetNumber());
                sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
                sb.append(location.getUserIndoorState());
                sb.append("\nDirection(not all devices have value): ");
                sb.append(location.getDirection());// 方向
                sb.append("\nlocationdescribe: ");
                sb.append(location.getLocationDescribe());// 位置语义化信息
                sb.append("\nPoi: ");// POI信息
                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < location.getPoiList().size(); i++) {
                        Poi poi = (Poi) location.getPoiList().get(i);
                        sb.append("poiName:");
                        sb.append(poi.getName() + ", ");
                        sb.append("poiTag:");
                        sb.append(poi.getTags() + "\n");
                    }
                }
                if (location.getPoiRegion() != null) {
                    sb.append("PoiRegion: ");// 返回定位位置相对poi的位置关系，仅在开发者设置需要POI信息时才会返回，在网络不通或无法获取时有可能返回null
                    PoiRegion poiRegion = location.getPoiRegion();
                    sb.append("DerectionDesc:"); // 获取POIREGION的位置关系，ex:"内"
                    sb.append(poiRegion.getDerectionDesc() + "; ");
                    sb.append("Name:"); // 获取POIREGION的名字字符串
                    sb.append(poiRegion.getName() + "; ");
                    sb.append("Tags:"); // 获取POIREGION的类型
                    sb.append(poiRegion.getTags() + "; ");
                    sb.append("\nSDK版本: ");
                }
                sb.append(locationService.getSDKVersion()); // 获取SDK版本
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 速度 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());// 卫星数目
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 海拔高度 单位：米
                    sb.append("\ngps status : ");
                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    if (location.hasAltitude()) {// *****如果有海拔高度*****
                        sb.append("\nheight : ");
                        sb.append(location.getAltitude());// 单位：米
                    }
                    sb.append("\noperationers : ");// 运营商信息
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                LoggerUtils.e("定位的结果" + sb.toString());
                if (!TextUtils.isEmpty(location.getCity())) {
                    SPLocationData spLocationData = SPLocationData.nSPLocationDataInstance();
                    spLocationData.setProvince(location.getProvince());
                    spLocationData.setTime(location.getTime());
                    spLocationData.setCity(location.getCity());
                    spLocationData.setAddr(location.getAddrStr());
                    spLocationData.setDistrict(location.getDistrict());
                    spLocationData.setLatitude(String.valueOf(location.getLatitude()));
                    spLocationData.setLontitude(String.valueOf(location.getLongitude()));
                    spLocationData.setStreet(location.getStreet());
                    spLocationData.setIsLocation(1);
                    spLocationData.upSPLocationData();
                    if (!TextUtils.isEmpty(LoginHelper.getLocationInfo().getLontitude()) && !TextUtils.isEmpty(LoginHelper.getLocationInfo().getLatitude())) {
                        locationService.stop();
                        LoggerUtils.e("Myapp保存定位的数据：" + LoginHelper.getLocationInfo().getLatitude() + "----" + LoginHelper.getLocationInfo().getLontitude());
                        RxBus.getDefault().post(new RxBusBean(200, 200, "location"));

                    }
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }

        /**
         * 回调定位诊断信息，开发者可以根据相关信息解决定位遇到的一些问题
         * @param locType 当前定位类型
         * @param diagnosticType 诊断类型（1~9）
         * @param diagnosticMessage 具体的诊断信息释义
         */
        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
//            int tag = 2;
//            StringBuffer sb = new StringBuffer(256);
//            sb.append("诊断结果: ");
//            if (locType == BDLocation.TypeNetWorkLocation) {
//                if (diagnosticType == 1) {
//                    sb.append("网络定位成功，没有开启GPS，建议打开GPS会更好");
//                    sb.append("\n" + diagnosticMessage);
//                } else if (diagnosticType == 2) {
//                    sb.append("网络定位成功，没有开启Wi-Fi，建议打开Wi-Fi会更好");
//                    sb.append("\n" + diagnosticMessage);
//                }
//            } else if (locType == BDLocation.TypeOffLineLocationFail) {
//                if (diagnosticType == 3) {
//                    sb.append("定位失败，请您检查您的网络状态");
//                    sb.append("\n" + diagnosticMessage);
//                }
//            } else if (locType == BDLocation.TypeCriteriaException) {
//                if (diagnosticType == 4) {
//                    sb.append("定位失败，无法获取任何有效定位依据");
//                    sb.append("\n" + diagnosticMessage);
//                } else if (diagnosticType == 5) {
//                    sb.append("定位失败，无法获取有效定位依据，请检查运营商网络或者Wi-Fi网络是否正常开启，尝试重新请求定位");
//                    sb.append(diagnosticMessage);
//                } else if (diagnosticType == 6) {
//                    sb.append("定位失败，无法获取有效定位依据，请尝试插入一张sim卡或打开Wi-Fi重试");
//                    sb.append("\n" + diagnosticMessage);
//                } else if (diagnosticType == 7) {
//                    sb.append("定位失败，飞行模式下无法获取有效定位依据，请关闭飞行模式重试");
//                    sb.append("\n" + diagnosticMessage);
//                } else if (diagnosticType == 9) {
//                    sb.append("定位失败，无法获取任何有效定位依据");
//                    sb.append("\n" + diagnosticMessage);
//                }
//            } else if (locType == BDLocation.TypeServerError) {
//                if (diagnosticType == 8) {
//                    sb.append("定位失败，请确认您定位的开关打开状态，是否赋予APP定位权限");
//                    sb.append("\n" + diagnosticMessage);
//                }
//            }
//            LoggerUtils.e("定位的诊断结果：" + sb.toString());
        }
    };

    //同意之后
    @NeedsPermission({Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
    void initPermission() {
        onStart();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
    void onShowRationale(final PermissionRequest request) {
        SelectDialog.show(getMe(), "提示", "需开启定位权限，请打开再使用", "立即打开", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                request.proceed();
            }
        }, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                request.cancel();
            }
        }).setCanCancel(false);
    }


    @OnNeverAskAgain({Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
//用户选择的不再询问
    public void StorageNeverAsk() {
        SelectDialog.show(getMe(), "提示", "已被拒绝,如需使用,请手动开启定位权限", "设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Uri packageURI = Uri.parse("package:" + "com.cn.easypaper");
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        }, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        }).setCanCancel(false);
    }

    /**
     * 退出
     */
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - exitTime) < 2000) {
            super.onBackPressed();
            finishAll();
            Process.killProcess(Process.myPid());
            Runtime.getRuntime().gc();
        } else {
            RxToast.success("再按一次退出程序");
            exitTime = currentTime;
        }
    }


}
